package com.frxuexi.park2210.vistor

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.frxuexi.lib_base.entity.VistorBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.net.Const
import com.frxuexi.park2210.R
import com.frxuexi.park2210.adapter.VistorAdapter
import com.frxuexi.park2210.databinding.ActivityVistorBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/app/VistorActivity")
@AndroidEntryPoint
class VistorActivity : BaseActivity<ActivityVistorBinding,VistorViewModel>(){
    val vistorAdapter by lazy { VistorAdapter() }
    override fun initData() {
        vm.getVistorsSuc.observe(this){
            val vistorBean = Gson().fromJson(it, VistorBean::class.java)
            vistorAdapter.addData(vistorBean)
            vistorAdapter.notifyDataSetChanged()
        }

        vm.deleteVistorSuc.observe(this){
            Log.i("===",it)
        }

    }

    override fun initView() {
        binding.headerVistor.apply {
            headerBack.setOnClickListener {
                finish()
            }
            headerTitle.setText("来访预约")
            headerAdd.visibility=View.VISIBLE
            headerAdd.setOnClickListener {
                ARouter.getInstance().build("/app/VistorAddActivity").navigation()
            }
        }

        binding.rvVistor.apply {
            adapter=vistorAdapter
            layoutManager=LinearLayoutManager(this@VistorActivity)
        }

        //左滑删除
        val touchHelper = ItemTouchHelper(object : SimpleCallback(0, ItemTouchHelper.LEFT) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                vm.deleteVistor(mapOf("visitorId" to vistorAdapter.data.get(position).visitorId) )
                vistorAdapter.data.removeAt(position)
                vistorAdapter.notifyItemRemoved(position)

            }

        })

        touchHelper.attachToRecyclerView(binding.rvVistor)


    }

    override fun onResume() {
        super.onResume()
        vistorAdapter.data.clear()
        vm.getVistors(mapOf("userId" to SPUtils.getInstance().getInt(Const.UID)))
    }

}